import re
from rest_framework import serializers
from django.conf import settings
from celery_tasks.email.tasks import send_verify_email
from goods.models import SKU
from users.constants import USER_BROWSING_HISTORY_COUNTS_LIMIT
from users.models import User, Address
from django_redis import get_redis_connection


class BrowseHistorySerializer(serializers.Serializer):
    # 保存浏览记录的序列化器类
    sku_id = serializers.IntegerField(label='商品id')
    def validate_sku_id(self, value):
        try:
            sku = SKU.objects.get(id=value)
        except SKU.DoesNotExist:
            raise serializers.ValidationError('商品不存在')
        return value
    def create(self, validated_data):
        redis_conn = get_redis_connection('histories')
        user_id = self.context['request'].user.id
        # 先清空所有存在过的sku_id lrem(name, count, value)
        # 三个参数:redis的key,count:0表示全删 1表示从左边到右边删除一次 -1从右到左删一次, value 哪个值
        redis_conn.lrem('history_%s'%user_id, 0, validated_data['sku_id'])
        #从左添加数据lpush(name, value)
        redis_conn.lpush('history_%s'%user_id, validated_data['sku_id'])
        # 只保留五个,截取列表下标0开始 ltrim(name, start, end)
        redis_conn.ltrim('history_%s'%user_id, 0, USER_BROWSING_HISTORY_COUNTS_LIMIT-1)
        return validated_data
# redis_conn.lrange('history_1',, 0, -1)

class AddressSerializer(serializers.ModelSerializer):
    province_id = serializers.IntegerField(label='省id')
    city_id = serializers.IntegerField(label='市id')
    district_id = serializers.IntegerField(label='区id')
    province = serializers.StringRelatedField(label='省', read_only=True)
    city = serializers.StringRelatedField(label='市', read_only=True)
    district = serializers.StringRelatedField(label='区', read_only=True)
    class Meta:
        model = Address
        exclude = ('user', 'is_deleted', 'create_time', 'update_time')
    def validate_mobile(self, value):
        if not re.match(r'^1[3-9]\d{9}$',value):
            return serializers.ValidationError({'message': '手机号格式不正确'})
        return value
    def create(self, validated_data):
        user = self.context.get('request').user # 调用context额外参数通过self, get_serializer()里已经定义了context里的参数
        validated_data['user'] = user
        addr = super().create(validated_data)
        return addr

class AddressTitleSerializer(serializers.ModelSerializer):
    class Meta:
        model = Address
        fields = ('id', 'title', )

class UserSerializer(serializers.ModelSerializer):
    password2 = serializers.CharField(label='密码', write_only=True)
    sms_code = serializers.CharField(label='验证码', write_only=True)
    allow = serializers.CharField(label='是否同意协议', write_only=True)
    token = serializers.CharField(label='JWT token', read_only=True)
    class Meta:
        model = User
        fields = ('id', 'username', 'password', 'password2', 'mobile', 'sms_code', 'allow', 'token')
        extra_kwargs = {
            'username': {
                'min_length': 5,
                'max_length': 20,
                'error_messages': {
                    'min_length': '仅允许5-20个字符的用户名',
                    'max_length': '仅允许5-20个字符的用户名',
                }
            },
            'password': {
                'write_only': True,
                'min_length': 8,
                'max_length': 20,
                'error_messages': {
                    'min_length': '仅允许8-20个字符的密码',
                    'max_length': '仅允许8-20个字符的密码',
                }
            }
        }
    # 1 校验参数(判断参数完整性,用户名不能全为数字,两次密码是否相同,手机号格式,短信验证码,是否同意协议,)
    def validate_username(self, value):
        username = re.match(r'^\d+$', value)
        if username:
            raise serializers.ValidationError('用户名不能为纯数字')
        return value
    def validate(self, attrs):
        password = attrs['password']
        password2 = attrs['password2']
        if password != password2:
            raise serializers.ValidationError('两次密码不一致')

        mobile = attrs['mobile']
        if re.match(r'^1[3-9]\d{9}$', mobile) is None:
            raise serializers.ValidationError('手机号格式不正确')

        allow = attrs['allow']
        if allow != 'true':
            raise serializers.ValidationError('用户没有同意协议')

        # 短信验证码
        redis_con = get_redis_connection('sms_code')
        # redis_line.setex('sms_%s' % mobile, constants.SMS_CODE_REDIS_EXPIRES, security_code)
        sms_code = redis_con.get('sms_%s' % mobile)
        if sms_code is None:
            raise serializers.ValidationError('验证码已失效')
        if sms_code.decode() != attrs['sms_code']:
            raise serializers.ValidationError('验证码不一样')

        return attrs

    def create(self, validated_data):
        # 清除不需要保存的数据
        del validated_data['password2']
        del validated_data['sms_code']
        del validated_data['allow']

        user = User.objects.create_user(**validated_data)

        from rest_framework_jwt.settings import api_settings

        # # 生成payload的方法
        # jwt_payload_handler = api_settings.JWT_PAYLOAD_HANDLER
        # # 生成jwt token的方法
        # jwt_encode_handler = api_settings.JWT_ENCODE_HANDLER
        #
        # # 生成payload
        # payload = jwt_payload_handler(user)
        # # 生成jwt token
        # token = jwt_encode_handler(payload)
        from rest_framework_jwt.settings import api_settings

        jwt_payload_handler = api_settings.JWT_PAYLOAD_HANDLER
        jwt_encode_handler = api_settings.JWT_ENCODE_HANDLER

        payload = jwt_payload_handler(user)
        token = jwt_encode_handler(payload)
        user.token = token
        return user

class UserDetailSerializer(serializers.ModelSerializer):

    class Meta:
        model = User
        fields = ('id', 'username', 'mobile', 'email', 'email_active')

class EmailSerializer(serializers.ModelSerializer):
    class Meta:
        model = User
        fields = ('id', 'email')
        # email = EmailField(allow_blank=True, label='电子邮件地址', max_length=254, required=False)
        # 因为django给我们创建的email是可以为空的
        # 所以得更改为必须填写
        extra_kwargs = {
            'email':{
                'required': True
            }
        }

    def update(self, instance, validated_data):
        # 因为需要发送验证邮件 所以重写update方法
        instance.email = validated_data.get('email')
        instance.save()
        send_verify_email.delay(instance.email, instance.generate_verify_email_url())
        return instance
